package com.tpc.control.sap;

import com.sap.conn.jco.AbapException;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

public class ZBapiGetCustomerList {
	private String customerId;
	private JCoTable idRange;
	private JCoTable addressData;
	private JCoTable specialData;
	private JCoTable kna1Tab;

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public JCoTable getIdRange() {
		return idRange;
	}

	public JCoTable getAddressData() {
		return addressData;
	}

	public JCoTable getSpecialData() {
		return specialData;
	}

	public JCoTable getKna1Tab() {
		return kna1Tab;
	}

	public ZBapiGetCustomerList(String customerId) {
		super();
		this.customerId = customerId;
	}
	
	public void execute(SapConnector connector) throws JCoException {
		JCoDestination destination = JCoDestinationManager
				.getDestination(connector.getMyDestinationName());
		JCoFunction function = destination.getRepository().getFunction(
				"Z_BAPI_GET_CUSTOMER_LIST");
		
		
		
		if (function == null)
			throw new RuntimeException("Z_BAPI_DOWNLOAD_PROD_BEAM not found in SAP.");

		idRange = function.getTableParameterList().getTable("IDRANGE");
		idRange.appendRow();
		idRange.setValue("SIGN", "I");
		idRange.setValue("OPTION", "EQ");
		idRange.setValue("LOW", customerId);
		
		try {
			function.execute(destination);
		} catch (AbapException e) {
			System.out.println(e.toString());
			return;
		}

		addressData = function.getTableParameterList().getTable("ADDRESSDATA");
		specialData = function.getTableParameterList().getTable("SPECIALDATA");
		kna1Tab = function.getTableParameterList().getTable("KNA1_TAB");
	}
	
	public static void main(String[] args) {
		SapConnector connector = new SapConnector("ABAP_AS_WITHOUT_POOL", "192.168.42.188", "tprfc", "tpcork");
		ZBapiGetCustomerList bapi = new ZBapiGetCustomerList("0090100001");
		try {
			bapi.execute(connector);
			
			for (int i = 0; i < bapi.getKna1Tab().getNumRows(); i++) {
				bapi.getKna1Tab().setRow(i);
				System.out.println(bapi.getKna1Tab().getString("NAME1") + '\t'
						+ bapi.getKna1Tab().getString("NAME2"));
			}
			
		} catch (JCoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
